/**
 * Created by Freeman on 2017/3/16.
 */
import uaParser from 'ua-parser-js' // 客户端浏览器信息解析模块
import CryptoJS from "crypto-js"    // åŠ å¯†æ¨¡å—
import * as constants from '../../src/AppConstants'
import * as types from '../store/types'
import Moment from 'moment'

/**
 * APIæŽ¥å£å‚æ•°ç­¾å
 * @param  {[Object]} params [è¯·æ±‚å‚æ•°]
 * @return {[String]}        [å‚æ•°ç­¾åå­—ç¬¦ä¸²]
 */
const getSign = function (params) {
  let paramMap = new Map()
  for (let key in params) {
    if (key == constants.PARAM_SIGN_NAME) {
      continue
    }
    let value = params[key]
    if (!value) {
      value = ''
      params[key] = ''
    }
    paramMap.set(key, value)
  }

  if (paramMap.size < 1) {
    return null
  }

  let str = ''

  // 1ã€æŽ’åº
  let orderParamMap = new Map([...paramMap.entries()].sort())
  // 2ã€ç”¨&ç¬¦å·æ‹¼æŽ¥
  for (let [key, value] of orderParamMap) {
    str += `${key}=${value}&`
  }
  str += constants.SIGN_SECURITY_KEY	// æœ€åŽæ‹¼æŽ¥åŠ å¯†å¯†é’¥
  // 3ã€ç­¾å
  let sign = CryptoJS.MD5(str).toString()
  return sign
}

// èŽ·å–å½“å‰å®¢æˆ·ç«¯æ‰€å¤„çš„æ¸ é“
const getChannel = function () {
  if (isWeChat()) {
    return '1'  // å¾®ä¿¡
  } else {
    return '5'  // H5/PC
  }
}

/**
 * èŽ·å–urlä¸­å‚æ•°
 * @returns {Object} å°†urlå‚æ•°ç”¨é”®å€¼å¯¹çš„æ–¹å¼å­˜å‚¨
 */
const getUrlParams = function (url) {
  url = url || window.location.href   //èŽ·å–urlä¸­"?"ç¬¦åŽçš„å­—ä¸²
  if (url.indexOf("#") > -1) {
    url = url.split('#')[1]
  }
  let params = new Object()
  if (url.indexOf("?") != -1) {
    let strs = url.substr(url.indexOf("?") + 1).split("&")
    for (var i = 0; i < strs.length; i++) {
      params[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1])
    }
  }
  return params;
}

/**
 * å½“å‰æµè§ˆå™¨æ˜¯å¦å¾®ä¿¡å®¢æˆ·ç«¯
 * @returns {boolean} å¾®ä¿¡å®¢æˆ·ç«¯è¿”å›žtrueï¼Œå¦åˆ™è¿”å›žfalse
 */
const isWeChat = function () {
  let ua = uaParser(navigator.userAgent)
  let browserName = ua.browser.name
  return browserName == 'WeChat'
}

/**
 * ä¸´æ—¶ä¿å­˜é‡ç½®å¯†ç çš„keyå’Œæ‰‹æœºå·
 * @param phone
 * @param key
 */
const storeResetPwdInfo = function (phone, key) {
  localStorage.setItem(constants.RESET_PWD_KEY, key)
  localStorage.setItem(constants.RESET_PWD_PHONE, phone)
}

/**
 * èŽ·å–é‡ç½®å¯†ç ä¸´æ—¶ä¿å­˜çš„keyå’Œæ‰‹æœºå·
 * @returns {{phone, key}}
 */
const getResetPwdInfo = function () {
  return {
    phone: localStorage.getItem(constants.RESET_PWD_PHONE),
    key: localStorage.getItem(constants.RESET_PWD_KEY)
  }
}

/**
 * æ¸…é™¤é‡ç½®å¯†ç ä¸´æ—¶ä¿å­˜çš„keyå’Œæ‰‹æœºå·
 */
const clearResetPwdInfo = function () {
  localStorage.removeItem(constants.RESET_PWD_KEY)
  localStorage.removeItem(constants.RESET_PWD_PHONE)
}


/**
 * 性別数据
 * @type {{1: 男, 2: 女}}
 */
const GENDER = {}
GENDER[constants.GENDER_MEN] = '男'
GENDER[constants.GENDER_WOMEN] = '女'

/**
 * 是否登录
 * @param state
 * @returns {boolean} 已经登录返回true，否则返回false
 */
const isLogin = function () {
  let apiToken = localStorage.getItem(constants.API_TOKEN)
  //let userInfo = localStorage.getItem(constants.USER_INFO)
  return apiToken && apiToken.length === 191
}

/**
 * 获取用户标标样式
 * @param type
 * @returns {*}
 */
const getUserTagStyle = function (type) {
  if (type == constants.USERTYPE_LEADER_TEACHER) {
    return "role-mark green";
  } else if (type == constants.USERTYPE_TEACHER) {
    return "role-mark blue";
  } else {
    return "role-mark orange";
  }
}

/**
 * 获取选择的课程
 * @see grade_modules.js#state.course
 * @param course 课程信息
 */
const getSelectedCourse = function (course) {
  let courseList = []
  course.selected.forEach((function (courseId) {
    course.list.forEach(function (courseItem) {
      if (courseId == courseItem.id) {
        courseList.push(courseItem.name)
      }
    })
  }))
  course.addSelected.forEach(function (courseName) {
    courseList.push(courseName)
  })
  return courseList
}

const copyObject = function (source, target) {
  let props = Object.getOwnPropertyNames(source);
  for (let i = 0; i < props.length; i++) {
    let property = props[i]
    let value = source[property]
    if (typeof String.prototype.startsWith != 'function') {
      String.prototype.startsWith = function (str) {
        var reg = new RegExp("^" + str);
        return reg.test(this);
      }
    }
    if (property.startsWith('_')) {
      continue
    }
    if (Array.isArray(value)) {
      if (!target[property]) {
        target[property] = []
      }
      for (let j = 0; j < value.length; j++) {
        let subObj = {}
        target[property].push(subObj)
        copyObject(value[j], subObj)
      }
    } else {
      target[property] = value
    }
  }
}

/**
 * 重置对象所有属性默认值
 * @param object
 */
const resetObject = function (object) {
  if (!object && typeof(object) != 'object') {
    return
  }

  for (let prop in object) {
    let value = object[prop]
    if (typeof(value) === 'string') {
      object[prop] = ''
    } else if (Array.isArray(value)) {
      object[prop].splice(0, object[prop].length)
    } else if (typeof(value) === 'number') {
      object[prop] = 0
    } else if (typeof(value) === 'boolean') {
      object[prop] = false
    } else if (typeof(value) === 'object') {
      resetObject(value)
    } else {
      object[prop] = null
    }
  }
}

/**
 * 显示对话框
 * @param store         状态对象
 * @param title         标题
 * @param content       内容
 * @param leftBtnText   左边按钮文本
 * @param leftBtnEvent  左边按钮点击事件
 * @param rightBtnText  右边按钮文本
 * @param rightBtnEvent 左边按钮点击事件
 */
const showDialog = function (store, title, content, leftBtnText, leftBtnEvent, rightBtnText, rightBtnEvent) {
  store.commit(types.UPDATE_CONFIRM, {
    show: true,
    title: title,
    content: content,
    leftBtnText: leftBtnText,
    leftBtnEvent: leftBtnEvent,
    rightBtnText: rightBtnText,
    rightBtnEvent: rightBtnEvent
  })
}

/**
 * 显示对话框
 * <p>左边按钮默认文字为：确认</p>
 * <p>右边按钮默认文字为：取消</p>
 * @param store
 * @param title         标题
 * @param content       内容
 * @param leftBtnEvent  左边按钮事件
 * @param rightBtnEvent 右边按钮事件
 */
const showDialog2 = function (store, title, content, leftBtnEvent, rightBtnEvent) {
  showDialog(store, title, content, constants.DIALOG_BTN_CONFIRM, leftBtnEvent, constants.DIALOG_BTN_CANCEL, rightBtnEvent)
}

/**
 * 添加新的标签
 * @param tags 源标签
 * @param newTags 新标签列表
 */
const addTags = function (tags, newTags) {
  if (!(tags && newTags && Array.isArray(tags) && Array.isArray(newTags))) {
    console.warn('无效的tags', tags, newTags)
    return tags
  }
  for (let i = 0; i < newTags.length; i++) {
    let newTag = newTags[i]
    let exists = tags.findIndex(function (oldTag) {
        return oldTag.tag == newTag.tag && oldTag.type == newTag.type
      }) != -1
    if (!exists) {
      tags.push(newTag)
    }

    // 如果是老师身份，还需要将课程科目做为标签添加到用户身份
    if ((newTag.type == constants.USERTYPE_LEADER_TEACHER || newTag.type == constants.USERTYPE_TEACHER)
      && newTag.subjects && Array.isArray(newTag.subjects)) {
      addTags(tags, newTag.subjects)
    }
  }
}

/**
 * 根据用户所有标签，查询用户的身份信息，是否包含老师或家长身份
 * @param tags
 */
const getIdentitiesByTags = function (tags) {
  let identities = {isTeacher: false, isParent: false}
  if (!(tags && Array.isArray(tags))) {
    return identities
  }
  tags.forEach((tag) => {
    if (tag.type == constants.USERTYPE_LEADER_TEACHER || tag.type == constants.USERTYPE_TEACHER) {
      identities.isTeacher = true
    } else if (tag.type == constants.USERTYPE_PARENT) {
      identities.isParent = true
    }
  })
  return identities
}

/**
 * 是否加入该班级
 * @param status 在该班级的状态
 * @returns {boolean} true：已经加入，false:未加入
 */
const isJoinedGrade = function (status) {
  return status == constants.GRADE_STATUS_JOINED
}

/**
 * 是否处于审核中
 * @param status 在该班级的状态
 * @returns {boolean} true表示在审核中，否则返回false
 */
const isApplyingGrade = function (status) {
  return status == constants.GRADE_STATUS_APPLYING
}

/**
 * 是否申请失败
 * @param status 在该班级的状态
 * @returns {boolean} true表示申请失败，否则返回false
 */
const isRejectGrade = function (status) {
  return status == constants.GRADE_STATUS_REJECTED
}

/**
 * 是否老师身份
 * @param type 身份类型
 */
const isTeacher = function (type) {
  return type == constants.USERTYPE_LEADER_TEACHER || type == constants.USERTYPE_TEACHER
}

/**
 * 格式化日期
 * @param value     日期毫秒值
 * @param format    格式
 * @returns {string}
 */
const formatDate = function (value, format) {
  if (!value) {
    return ''
  }

  format = format || 'YYYY-MM-DD hh:mm:ss'
  return Moment(Number(value)).format(format)
}

/**
 * 排序班级列表
 * @param classList
 * @returns {Array.<T>|*}
 */
const sortClassList = function (classList) {
  return classList.sort(function (clazzA, clazzB) {
    if (clazzA.status == constants.GRADE_STATUS_JOINED) {
      return -1
    } else {
      if (clazzB.status == constants.GRADE_STATUS_REJECTED) {
        return -1
      } else {
        return 1
      }
    }
  })
}

/**
 * 整理预览图片数据
 * @param targetImgList 当前预览的图片列表
 * */
const copyImgList = function (targetImgList) {
  let imgListArr = [];
  targetImgList.forEach(function (item) {
    let imgListObj = {};
    imgListObj['src'] = item.url;
    imgListObj['w'] = item.width;
    imgListObj['h'] = item.height;
    imgListArr.push(imgListObj)
  });
  return imgListArr
}

/**
 * 调用函数
 * @param fun 函数引用
 * @param args 函数参数
 */
const callFun = function (fun, ...args) {
  fun && typeof(fun) === 'function' && fun(...args)
}

/**
 * 获取最后一次使用的手机号
 */
const getLastUsePhone = function () {
  return localStorage.getItem(constants.CACHE_LAST_USE_LOGIN_PHONE) || ''
}

/**
 * 设置最后一次使用的手机号
 */
const storageLastUsePhone = function (phone) {
  return localStorage.setItem(constants.CACHE_LAST_USE_LOGIN_PHONE, phone || '')
}


/**
 * 将好友信息包装成缓存的数据结构
 * @param uid   用户ID
 * @param friend 好友信息
 * @returns {{uid: *, fid, name, avatar: (*|methods.avatar|computed.avatar|avatar|string|string), identityTag: *, lastTime: string, lastMsg: string, unread: number}}
 */
const getFriendCacheData = function (uid, friend) {
  return {
    uid: String(uid),
    fid: String(friend.id),
    name: friend.name,
    avatar: friend.avatar,
    identityTag: friend.identityTag,
    lastTime: friend.lastTime || '',
    lastMsg: friend.lastMsg || '',
    unread: friend.unread || 0
  }
}

/**
 * 合并用户身份的所有标签
 * @param tags
 * @returns {Array}
 */
const mergerTags = function (tags) {
  let tagsArray = [];
  tags.forEach((item) => {
    if (item.subjects) {
      item.subjects.forEach((subItem) => {
        tagsArray.push(subItem)
      })
    } else {
      tagsArray.push(item)
    }
  });
  return tagsArray
}

/**
 * 存储用户信息到localStorage
 * @param data  用户信息
 * @param phone 手机号
 */
const storageUserInfo = function (data, phone) {
  let apiToken = data.token
  localStorage.setItem(constants.API_TOKEN, apiToken)
  storageLastUsePhone(phone)
}


/**
 * 校验手机号
 * @param phone
 */
const checkPhone = function (phone) {
  return /^1[34578]\d{9}$/.test(phone)
}

/**
 * 除内容高度（窗口高度-header高度-footer高度）
 * @return {number}
 */
const getContentHeight = function () {
  let contentHeight = document.documentElement.clientHeight
  let headerView = document.getElementsByClassName('vux-header-box')
  if (headerView && headerView.length > 0) {
    contentHeight -= headerView[0].clientHeight
  }
  let footerView = document.getElementsByClassName('weui_tabbar')
  if (footerView && footerView.length > 0) {
    contentHeight -= footerView[0].clientHeight
  }
  return contentHeight
}
function imgEven(item, imgLength) {
  let originHeight = item.height;               //图片原始的高度
  let originWidth = item.width;                 //图片原始的宽度
  let imgWrapHeight;                            //图片的容器高度
  let imgWrapWidth;                             //图片的容器宽度
  let clientWidth = document.body.clientWidth;  //屏幕的宽度
  if (imgLength == 1) {
    imgWrapWidth = clientWidth - 20;
  } else if (imgLength == 2 || imgLength == 4) {
    imgWrapWidth = (clientWidth - 30) / 2;
  } else {
    imgWrapWidth = (clientWidth - 40) / 3;
  }
  imgWrapHeight = imgWrapWidth;
  if (originWidth > originHeight) {
    return {marginLeft: (imgWrapWidth - (originWidth * imgWrapHeight / originHeight)) / 2 + 'px', height: '100%'}
  } else if (originWidth < originHeight) {
    return {marginTop: (imgWrapWidth - (imgWrapWidth * originHeight / originWidth)) / 2 + 'px', width: '100%'}
  } else {
    return {height: '100%', width: '100%'}
  }
}
function imgWrapHeight(imgLength) {
  let clientWidth = document.body.clientWidth;
  let imgWrapWidth;
  if (imgLength == 1) {
    imgWrapWidth = clientWidth - 20;
  } else if (imgLength == 2 || imgLength == 4) {
    imgWrapWidth = (clientWidth - 30) / 2;
  } else {
    imgWrapWidth = (clientWidth - 40) / 3;
  }
  return {height: imgWrapWidth + "px"}
}

function isIOS() {
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/iPhone\sOS/i) == "iphone os") {
    return true;
  } else {
    return false;
  }
}

// 家长身份
const IDENTITY = {}
IDENTITY[constants.IDENTITY_FATHER] = '爸爸'
IDENTITY[constants.IDENTITY_MOM] = '妈妈'
IDENTITY[constants.IDENTITY_GRANDPA] = '爷爷'
IDENTITY[constants.IDENTITY_GRANDMA] = '奶奶'
IDENTITY[constants.IDENTITY_OTHER] = '其它'

// 用户类型
const USERTYPE = {}
USERTYPE[constants.USERTYPE_LEADER_TEACHER] = '班主任'
USERTYPE[constants.USERTYPE_TEACHER] = '任课老师'
USERTYPE[constants.USERTYPE_PARENT] = '家长'

export default {
  isWeChat,
  storeResetPwdInfo,
  clearResetPwdInfo,
  getResetPwdInfo,
  isLogin,
  GENDER,
  getSign,
  getChannel,
  getUrlParams,
  getUserTagStyle,
  IDENTITY,
  getSelectedCourse,
  copyObject,
  resetObject,
  USERTYPE,
  showDialog,
  showDialog2,
  addTags,
  getIdentitiesByTags,
  isJoinedGrade,
  isApplyingGrade,
  isRejectGrade,
  isTeacher,
  formatDate,
  sortClassList,
  copyImgList,
  callFun,
  getLastUsePhone,
  storageLastUsePhone,
  getFriendCacheData,
  mergerTags,
  storageUserInfo,
  checkPhone,
  getContentHeight,
  imgEven,
  imgWrapHeight,
  isIOS
}
